package gsw.demo.mvp.demo.retrofit;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import java.util.HashMap;

import gsw.demo.mvp.R;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Retrofit使用示例
 * 首先，下载依赖：
 * implementation 'com.squareup.retrofit2:retrofit:2.4.0'
 * implementation 'com.squareup.retrofit2:converter-scalars:2.4.0' //转换器：转换成string数据
 * implementation 'com.squareup.okhttp3:okhttp:3.10.0'
 * 然后，新建Service接口，设置请求方式和url
 * 然后，实例化Retrofit
 * 然后，实例化Service，用Service发送请求
 */
public class ActivityRetrofit extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit);
    }

    public void show1(View view) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://v.juhe.cn/weather/")
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();
        //和接口关联起来
        ApiService service = retrofit.create(ApiService.class);

        HashMap<String, Object> params = new HashMap<>();
        params.put("cityname", "长沙");
        params.put("key", "fd0f609b22905a0a56a48d7cf59a558b");

        service.sendRequest(params).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Toast.makeText(ActivityRetrofit.this, response.body(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }
}










